package com.cmcc.he.cz;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class LocalDataAdapter {

	private final Context mCtx;

	private SQLiteDatabase mDb;

	private DatabaseHelper mDbHelper;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL("create table local (_id integer primary key autoincrement, "
			        + "title text not null, body text not null);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub

		}

	}

	public LocalDataAdapter(Context ctx) {
		mCtx = ctx;
	}

	public LocalDataAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx, "local", null, 2);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}
	
	public long createNote(String title, String body) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("title", title);
        initialValues.put("body", body);

        return mDb.insert("local", null, initialValues);
    }
	
	public boolean updateNote(String title, String body) {
		try
		{
        ContentValues args = new ContentValues();
        args.put("title", title);
        args.put("body", body);

        return mDb.update("local", args, "title='" + title+"'", null) > 0;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
    }
	
	public Cursor fetchNote(String title) throws SQLException {
try{
        Cursor mCursor =
            mDb.query(true, "local", new String[] {"_id","body"}, "title='" + title+"'", null,
                    null, null, null, null);
        if (!mCursor.moveToFirst()) {
            createNote(title,"50");
            return fetchNote(title);
        }
        return mCursor;
}catch(Exception e){
	e.printStackTrace();
}
return null;

    }
}
